# coding=utf-8
import hashlib
import json
import random

import datetime
import requests
import tornado
from peewee import DoesNotExist

from db.model import Static, Article
from db.user import User

from libs.Tools import WashTools
from view import getMeta

from view.list_sub import getComments
from view.list_sub.hot import get_hot_page
from view.list_sub.news import get_news_page
from view.list_sub.person import get_person_page
from view.list_sub.tree import get_tree_page


class ListPage(tornado.web.RequestHandler):
    def get(self):
        # User.db.connect()

        meta = getMeta()
        if meta:
            qiniu_url = meta['domain']
            title = meta['title']
            headico = meta['headico']
            signature = meta.get('signature', '')

        else:
            self.redirect('/config')
            # User.db.close()
            return



        # 是否有个人信息页
        person_art = Article.filter(Article.path == '/_personal.md')
        if len(person_art) > 0:
            has_person = True
        else:
            has_person = False

        article_list = get_news_page()
        # hot_list = get_hot_page()
        hot_list = get_hot_page()
        folder_tree, time_tree = get_tree_page()
        # folder_tree, time_tree = get_tree_page()
        html = get_person_page(render=False)

        self.render('list.html', title=title, signature=signature, has_person=has_person,
                    headico=headico, article_list=article_list, hot_list=hot_list, folder_tree=folder_tree,
                    time_tree=time_tree, html=html)
        getComments()
        self.refresh_cache(qiniu_url)
        get_person_page(render=True)
        # User.db.close()

    def dealDic2List(self, dic):
        has_id = []
        for path, value in dic.iteritems():
            if not path.endswith('.md'):
                continue
            del value['hash']
            has_id.append(WashTools.washHeader2Field(value, path))

        return has_id

    def refresh_cache(self,qiniu_url):
        req_url = qiniu_url + '/.sunjian/list.json'.replace('/', '%2f') + '?v=' + str(random.random())
        try:
            list_etag = Static.get(Static.key == 'list_etag')
            etag = list_etag.value
        except DoesNotExist:
            etag = ''
        # req=None
        req = requests.get(url=req_url, headers={"If-None-Match": etag})
        print req.status_code
        print req_url
        if req.status_code == 404:
            self.redirect('/config')
            # User.db.close()
            return
        elif req.status_code == 304:
            list_str = Static.get(Static.key == 'list_str')
        else:
            req.encoding = 'utf8'
            list_etag_new = req.headers['etag']
            list_str = req.text
            list_dic = json.loads(list_str)
            hasId_list = self.dealDic2List(list_dic)
            with User.db.transaction() as txn:
                for li in hasId_list:
                    li['list_etag'] = list_etag_new

                    # art=Article.create(**li)
                    art = Article.create_or_get(**li)

                    # if not art[1]:
                    art = art[0]

                    art.title = li.get('title', '')
                    art.comments = li.get('comments', '')
                    # date = li.get('date', datetime.datetime.fromtimestamp(time.time()))

                    art.date = li.get('date', datetime.datetime.now())
                    art.path = li.get('path', '')
                    art.descripition = li.get('descripition', '')
                    art.tags = li.get('tags', '')
                    art.list_etag = list_etag_new
                    art.save()
                txn.commit()
            query = Article.delete().where(Article.list_etag != list_etag_new)
            query.execute()

            # 保存缓存及缓存hash值，代码写的太烂了，先这样吧
            sta1 = Static.create_or_get(key='list_etag', value=list_etag_new)
            sta2 = Static.create_or_get(key='list_str', value=list_str)
            if not sta1[1]:
                sta1[0].value = list_etag_new
                sta1[0].save()
            if not sta2[1]:
                sta2[0].value = list_str
                sta2[0].save()